﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Common;
using MarginTrading.Services;

namespace MarginTrading.Forms
{
    public partial class AddConfig : Form
    {
        public AddConfig()
        {
            InitializeComponent();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (validateInputs() == false)
            {
                return;
            }

            Config config = new Config();

            config.Name = textBoxName.Text;
            config.Value = textBoxValue.Text;

            try
            {
                ConfigServices.Add(config);
            }
            catch (System.Exception ex)
            {
                if (ex.Message.StartsWith("ORA-00001: unique"))
                {
                    MessageBox.Show("Configuration " + textBoxName.Text + " already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Failed to create new configuration\nError: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return;
            }
            MessageBox.Show("Configuration added successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Close();
        }

        private bool validateInputs()
        {
            if (textBoxValue.Text == "")
            {
                MessageBox.Show("Enter configuration value", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (textBoxName.Text == "")
            {
                MessageBox.Show("Enter configuration name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;
        }
    }
}
